package com.sanuo.pico.utils;

import androidx.annotation.CallSuper;

import com.menu.app.MyApp;
import com.menu.app.event.MsgEvent;
import com.menu.app.event.work.RentEvent;
import com.menu.app.it.RentListener;
import com.menu.app.model.Models;
import com.menu.app.util.pipe.BasePortEventPipe;
import com.plata.base.aclr.common.SilentTask;
import com.plata.base.aclr.common.TaskEngine;
import com.sanuo.pico.event.VerEvent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class PortPipe extends BasePortEventPipe {

    static PortPipe instance;

    public static PortPipe getInstance() {
        if (instance == null) {
            instance = new PortPipe();
        }
        return instance;
    }

    private PortPipe() {
        super();
    }

    @Override
    public void doInit() {
        super.doInit();
        isStart = true;
        if (Const.is1315()) {
            Command.getRented();
        }
        goBack(() -> getCoreV());
    }

    private void getCoreV() {
        h.removeCallbacks(getVerRunnable);
        h.postDelayed(getVerRunnable, 150);
    }

    Runnable getVerRunnable = new Runnable() {
        @Override
        public void run() {
            Command.sendTouchEvent(0, 0x13);
            h.postDelayed(this, 220);
        }
    };

    Runnable getRentRunnable = new Runnable() {
        @Override
        public void run() {
            getRent();
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(VerEvent event) {
        h.removeCallbacks(getVerRunnable);
        if (isStart) {
            if (Const.currentPage >= 83 && Const.currentPage <= 86) {
                return;
            }
            h.removeCallbacks(getRentRunnable);
            h.postDelayed(getRentRunnable, 100);
        }
    }

    public void goBack(Runnable runnable) {
        if (runnable != null) {
            runnable.run();
        }
//        h.removeCallbacks(goBack);
//        h.post(goBack.setRunnable(runnable));
    }

    String lastAction;

    private void getRent() {
        /**
         * launch rent activity to obtain left rent point
         * */
        lastAction = MyApp.getApp().getString(com.menu.app.R.string.rent_config);
        new MsgEvent().postValue(lastAction);
        h.post(new Runnable() {
            @Override
            public void run() {
                Command.sendTouchEvent(0, 0x65);
                h.postDelayed(this, 1000);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RentEvent event) {
        h.removeCallbacksAndMessages(null);
        if (isStart) {
            isStart = false;
            Models.Companion.get().getPointLoadingEvent().postValue(false);
        } else if (rentOn != null) {
            setRent(event);
        }
    }

    private boolean setRent(RentEvent event) {
        if (rentOn == null) {
            return false;
        }
        if (event.getValue() == 1) {
            if (rentOn) {
                TaskEngine.getInstance().submit(new SilentTask("rent") {
                    @Override
                    public void runInBackground() throws Exception {
                        setRentValue();
                    }
                });
            } else {
                Command.sendTouchEvent(0, 0x5e);
            }
        } else {
            if (rentOn) {
                Command.sendTouchEvent(0, 0x5d);
            } else {
                rentOn = null;
                rentResult(true);
            }
        }
        return true;
    }

    private void setRentValue() {
        try {
            Command.sendTouchEvent(0, 0x5a);
            Thread.sleep(200);
            char[] as = (rentValue.get() + "").toCharArray();
            for (int i = 0; i < as.length; i++) {
                int j = as[i] - '0';
                Command.sendTouchEvent(0, 0x50 + j);
                Thread.sleep(200);
            }
            Command.sendTouchEvent(0, 0x5c);
            Thread.sleep(200);
            Command.sendTouchEvent(0, 0x43);
            Thread.sleep(200);
            h.post(() -> {
                rentResult(true);
            });
        } catch (Throwable e) {
            e.printStackTrace();
            h.post(() -> {
                rentResult(false);
            });
        } finally {
            rentOn = null;
        }
    }

    private void rentResult(boolean success) {
        for (RentListener listener : rentListener) {
            listener.onSetRent(success);
        }
        rentListener.clear();
    }

    @CallSuper
    @Override
    public boolean setRent(boolean on, long value, RentListener listener) {
        boolean bo = super.setRent(on, value, listener);
        if (!bo) {
            return false;
        }
        if (Const.is1315()) {
            Command.setRented(0);
        }
        h.postDelayed(() -> Command.sendTouchEvent(0, 0x65), 150);
        return true;
    }

    @Override
    protected void sendTouchEvent(byte data_H, byte data_L) {
        Command.sendTouchEvent((int) data_H, (int) data_L);
    }
}
